package com.itlong.cloud.controller.operate;

import com.itlong.cloud.POJO.DTO.operate.OperateActivitiesGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateActivitiesSaveDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateActivitiesGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateActivitiesServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * <desc>
 *      运营-运营管理模块-运营活动控制器
 * </desc>
 *
 * @createDate 2019/06/25
 */
@RestController
@RequestMapping("/marketer/activities/")
@RefreshScope
public class OperateActivitiesController extends BaseController{

    private static Logger LOG = LoggerFactory.getLogger(OperateActivitiesController.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    IOperateActivitiesServiceClient iOperateActivitiesServiceClient;

    /**
     * <desc>
     *      获取分页列表
     * </desc>
     *
     * @param dto 入参
     * @return
     * @author Qiang.S
     * @createDate 2019/06/25
     */
    @RequestMapping(path = "getActivitiesPage",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getActivitiesPage(OperateActivitiesGetPageDTO dto){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateActivitiesGetPageDTO.class,request);
            Page<OperateActivitiesGetPageVO> page=iOperateActivitiesServiceClient.getActivitiesPage(dto);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        } catch (Exception e) {
            throw new DataAccessException("【运营_运营管理_运营活动getActivitiesPage】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      添加
     * </desc>
     *
     * @param dto 内容
     * @return
     * @author Qiang.S
     * @createDate 2019/06/25
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_HOMEPAGE_OPERATE_LOG_SAVE)
    @RequestMapping(path = "save",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object save(OperateActivitiesSaveDTO dto){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateActivitiesSaveDTO.class,request);
            if (StringUtils.isBlank(dto.getActivitiesName())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_NAME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getImageStr())) {
                return new MessageVO(OperateErrorCodeEnum.HOMEPAGE_IMAGE_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getStartTime())) {
                return new MessageVO(OperateErrorCodeEnum.HOMEPAGE_STARTTIME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getEndTime())) {
                return new MessageVO(OperateErrorCodeEnum.HOMEPAGE_ENDTIME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getProjectId())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_PROJECTID_EMPTY_ERR.getErrorCode());
            }
            if (dto.getSkipFlag() == null) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_SKIPFLAG_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getContent())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_CONTENT_EMPTY_ERR.getErrorCode());
            }
            String[] imageStrS = dto.getImageStr().split(",");
            dto.setImageUrl(uploadImageFile(new BASE64Decoder().
                    decodeBuffer(imageStrS[1]), dto.getImageType(), FileCatalogEnum.HOME_PAGE_FILE));
            iOperateActivitiesServiceClient.save(dto);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_运营管理_运营活动save】添加失败",e);
        }
        return messageVO;

    }

    /**
     * <desc>
     *      修改
     * </desc>
     *
     * @param dto 启动页实体
     * @return
     * @author Qiang.S
     * @createDate 2019/06/25
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_HOMEPAGE_OPERATE_LOG_UPDATE)
    @RequestMapping(path = "update",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object update(OperateActivitiesSaveDTO dto){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateActivitiesSaveDTO.class,request);
            if (StringUtils.isBlank(dto.getActivitiesId())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_ID_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getActivitiesName())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_NAME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getStartTime())) {
                return new MessageVO(OperateErrorCodeEnum.HOMEPAGE_STARTTIME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getEndTime())) {
                return new MessageVO(OperateErrorCodeEnum.HOMEPAGE_ENDTIME_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getProjectId())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_PROJECTID_EMPTY_ERR.getErrorCode());
            }
            if (dto.getSkipFlag() == null) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_SKIPFLAG_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getContent())) {
                return new MessageVO(OperateErrorCodeEnum.ACTIVITIES_CONTENT_EMPTY_ERR.getErrorCode());
            }
            if (!StringUtils.isBlank(dto.getImageStr())) {
                String[] imageStrS = dto.getImageStr().split(",");
                dto.setImageUrl(uploadImageFile(new BASE64Decoder().
                        decodeBuffer(imageStrS[1]), dto.getImageType(), FileCatalogEnum.HOME_PAGE_FILE));
            }
            iOperateActivitiesServiceClient.update(dto);
            messageVO=new MessageVO(dto.getActivitiesId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-_运营管理_运营活动update】更新失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      查询单条活动信息
     * </desc>
     *
     * @param activitiesId 活动编号
     * @return
     * @author Qiang.S
     * @createDate 2019/06/25
     */
    @RequestMapping(path = "getOne",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getAppPackage(String activitiesId){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            activitiesId= request.getAttribute("activitiesId")==null?null:request.getAttribute("activitiesId").toString();
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iOperateActivitiesServiceClient.getOne(activitiesId));
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_运营活动getOne】获取单条失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      删除启动页
     * </desc>
     *
     * @param activitiesIds 活动编号,逗号分隔
     * @return
     * @author Qiang.S
     * @createDate 2019/06/25
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_HOMEPAGE_OPERATE_LOG_DELETE)
    @RequestMapping(path = "delete",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object delete(String activitiesIds){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            activitiesIds= request.getAttribute("activitiesIds")==null?null:request.getAttribute("activitiesIds").toString();
            iOperateActivitiesServiceClient.delete(activitiesIds);
            messageVO=new MessageVO(activitiesIds,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch(Exception e){
            throw new DataAccessException("【运营_运营管理_运营活动delete】删除失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      上传图片文件
     * <desc/>
     *
     * @param bytes 图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-18
     */
    private String uploadImageFile(byte[] bytes,String imageType, FileCatalogEnum fileCatalog){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );
        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }else {
                LOG.info(String.format("图片上传失败，returnCode: %s",returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }
}
